package com.kelaite.procurement.utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import ch.qos.logback.classic.Logger;

/**
 * dto transfer to do
 * 
 * do transfer to dto
 * @author yuanchangwei
 *
 */
public class ConvertUtil
{

	private static final Logger logger = (Logger) LoggerFactory.getLogger(ConvertUtil.class);

	/**
	 * 
	 * @param source
	 *            源对象
	 * @param clazz
	 *            目标对象class
	 * @param <T>
	 * @param <S>
	 * @return
	 */
	public static <T, S> T convertObj(S source, Class<T> clazz)
	{
		if (source == null)
		{
			return null;
		}
		T target = null;
		try
		{
			target = clazz.newInstance();
			BeanUtils.copyProperties(source, target);
		} catch (InstantiationException | IllegalAccessException e)
		{
			logger.error("convertObj error ", e);
		}
		return target;
	}

	/**
	 * 将一个对象集合转换成另外一个对象集合
	 * 
	 * @param sourceList
	 *            源对象
	 * @param clazz
	 *            目标对象class
	 * @param <T>
	 * @param <S>
	 * @return
	 */
	public static <T, S> List<T> convertList(List<S> sourceList, Class<T> clazz)
	{
		if (sourceList == null)
		{
			return Collections.emptyList();
		}
		int size = sourceList.size();
		List<T> targetList = new ArrayList<>(size);
		for (S source : sourceList)
		{
			try
			{
				T target = clazz.newInstance();
				BeanUtils.copyProperties(source, target);
				targetList.add(target);
			} catch (InstantiationException | IllegalAccessException e)
			{
				logger.error("convertObj error ", e);
			}
		}
		if (CollectionUtils.isEmpty(targetList))
		{
			return targetList;
		}
		return targetList;
	}
}